package dev.doris;

import org.apache.hadoop.hive.ql.exec.UDF;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CallDolphinschedulerProcessFn extends UDF {



    public String evaluate(String prefixurl, String token, String projectCode, String processDefinitionCode, String startParams) {

        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(prefixurl + "/projects/" + projectCode + "/executors/start-process-instance?failureStrategy=END&processInstancePriority=LOW&warningType=NONE&warningGroupId=1&processDefinitionCode=" + processDefinitionCode + "&startParams=" + startParams);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            connection.setRequestProperty("token", token);

            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error:"+e.getLocalizedMessage();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "Error:"+e.getLocalizedMessage();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "Error:"+e.getLocalizedMessage();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
}
